﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DOTNET101_Indexers
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }


//Indexers Overview
//Indexers enable objects to be indexed in a similar manner to arrays.

//A get accessor returns a value. A set accessor assigns a value.

//The this keyword is used to define the indexers.

//The value keyword is used to define the value being assigned by the set indexer.

//Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.

//Indexers can be overloaded.

//Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.


    class SampleCollection<T>
    {
        private T[] arr = new T[100];
        public T this[int i]
        {
            get
            {
                return arr[i];
            }
            set
            {
                arr[i] = value;
            }
        }
    }

    // This class shows how client code uses the indexer
    class TestIndexers
    {
        public static void Test()
        {
            SampleCollection<string> stringCollection = new SampleCollection<string>();
            stringCollection[0] = "Hello, World";
            System.Console.WriteLine(stringCollection[0]);
        }
    }


    // Indexer on an interface:
    public interface ISomeInterface
    {
        // Indexer declaration:
        int this[int index]
        {
            get;
            set;
        }
    }

    // Implementing the interface.
    class IndexerClass : ISomeInterface
    {
        private int[] arr = new int[100];
        public int this[int index]   // indexer declaration
        {
            get
            {
                // Check the index limits.
                if (index < 0 || index >= 100)
                {
                    return 0;
                }
                else
                {
                    return arr[index];
                }
            }
            set
            {
                if (!(index < 0 || index >= 100))
                {
                    arr[index] = value;
                }
            }
        }
    }

    class TestIndexerClass
    {
        public static void Test()
        {
            IndexerClass test = new IndexerClass();
            // Call the indexer to initialize the elements #2 and #5.
            test[2] = 4;
            test[5] = 32;
            for (int i = 0; i <= 10; i++)
            {
                System.Console.WriteLine("Element #{0} = {1}", i, test[i]);
            }
        }
    }
}
